/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, {Component} from 'react';
import {
    DeviceEventEmitter,
    Image,
    ListView,
    Platform,
    ScrollView,
    StyleSheet,
    Text,
    TouchableHighlight,
    View
} from 'react-native';
import StyleUtils from "../../../res/styles/StyleUtils";
import Navigation from "../../../custom/Navigation";
import ModalListUtils from "../../../utils/ModalListUtils";
import ViewUtils from "../../../utils/ViewUtils";
import IparNetwork, {SERVER_TYPE} from "../../../httpUtils/IparNetwork";
import CommonUtils from "../../../common/CommonUtils";
import I18n from "../../../res/language/i18n";
import IparInput from "../../../custom/IparInput";
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view'

let countryData = [];
let provinceData = [];
let cityData = [];
let districtData = [];
export default class UserEditAddress extends Component {
    constructor(props) {
        super(props);
        let userData = this.props.editData;
        let addrsss = ' ';
        let splitData = [];
        if (userData) {
            addrsss = userData && userData.address ? userData.address : '';
            splitData = addrsss.split(',');
        }
        let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        countryData = [];
        provinceData = [];
        cityData = [];
        districtData = [];
        this.state = {
            countrySource: ds,
            provinceSource: ds,
            citySource: ds,
            districtSource: ds,
            modalDialog: false,
            isDateTimePickerVisible: false,
            selectCountry: splitData[0] ? splitData[0] : I18n.t('default.selectCountry'),
            selectProvince: splitData[1] ? splitData[1] : I18n.t('default.selectProvince'),
            selectCity: splitData[2] ? splitData[2] : I18n.t('default.selectCity'),
            selectDistrictCity: splitData[3] ? splitData[3] : I18n.t('default.selectDistrict'),
            modalDataType: 'country',
            streetNumber: '',
            buildingName: '',
            postCode: '',
            statusCode: undefined,
            countryId: '',
            userId: '',
            cityType: false,
            districtType: false,


        };

        this.iparNetwork = new IparNetwork()
    }


    componentWillUnmount() {
        this.iparNetwork = null;

    }

    componentDidMount() {


        /*获取本地数据*/
        CommonUtils.getAcyncInfo('userInfo').then((result) => {
            let resultData = JSON.parse(result);
            this.getAddressInfo();
            this.setState({
                userName: resultData.user_name,
                userId: resultData.main_user_id,
                phoneNumber: resultData.mobile,
            });
        });

    }

    /*获取用户收货地址信息姐*/
    getAddressInfo() {
        CommonUtils.showLoading();

        this.iparNetwork.getRequest(SERVER_TYPE.logistics + 'region?')
            .then((result) => {
                for (i = 0; i < result.length; i++) {
                    countryData.push(result[i]);
                }

                CommonUtils.dismissLoading();
                this.setState({

                    countrySource: this.state.countrySource.cloneWithRows(result)
                });

            })
            .catch((error) => {
                CommonUtils.dismissLoading();

                console.log(error);
            })
    }


    /*获取用户收货地址信息姐*/
    getProvinceInfo(level, selectCountry) {
        CommonUtils.showLoading();

        this.iparNetwork.getRequest(SERVER_TYPE.logistics + 'region?', 'level=' + level + '&parent=' + selectCountry)
            .then((result) => {
                CommonUtils.dismissLoading();

                if (level === 1) {
                    provinceData = result;
                    this.setState({
                        provinceSource: this.state.provinceSource.cloneWithRows(result)
                    });


                } else if (level === 2) {
                    cityData = result;

                    if (result.length > 0) {
                        this.setState({
                            citySource: this.state.citySource.cloneWithRows(result),
                            cityType: true,
                        });
                    } else {
                        this.setState({cityType: false,});//cityCode: 'code'
                    }
                } else {
                    districtData = result;
                    if (result.length > 0) {
                        this.setState({
                            districtSource: this.state.districtSource.cloneWithRows(result),
                            districtType: true
                        });
                    } else {
                        this.setState({
                            districtType: false
                        });
                    }

                }

            })
            .catch((error) => {
                CommonUtils.dismissLoading();

                console.log(error)
            })
    }


    /*用户地址btn 点击*/
    editAddress() {
        CommonUtils.dismissLoading();

        this.getAddress();
    }

    /*修改地址接口*/
    getAddress() {

        CommonUtils.showLoading();
        let userData = this.props.editData;
        let addrsss = userData && userData.address ? userData.address : '';

        let _addressId = this.state.countryId;
        let _streetName = this.state.streetNumber ? this.state.streetNumber : userData && userData.street_name ? userData.street_name : '';
        let _building = this.state.buildingName ? this.state.buildingName : userData && userData.building ? userData.building : '';
        let _postCode = this.state.postCode ? this.state.postCode : userData && userData.postcode ? userData.postcode : '';
        let _address = this.state.selectCountry ? this.state.selectCountry + ',' + this.state.selectProvince + ',' + this.state.selectCity + ',' + this.state.selectDistrictCity : addrsss;

        let formData = new FormData();
        formData.append("user_id", this.state.userId);
        formData.append("address_id", _addressId);
        formData.append("street_name", _streetName);
        formData.append("building", _building);
        formData.append("postCode", _postCode);
        formData.append("address", _address);

        this.iparNetwork.getPostFrom(SERVER_TYPE.admin + 'updateUserInfo', formData)
            .then((result) => {
                CommonUtils.dismissLoading();
                if (result.code === 200) {

                    userData.address_id = _addressId;
                    userData.street_name = _streetName;
                    userData.building = _building;
                    userData.address = _address;

                    this.props.callback(userData);
                    this.props.navigator.pop();
                    DeviceEventEmitter.emit('toast', I18n.t('default.success'))
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
                }
            })
            .catch((error) => {
                CommonUtils.dismissLoading();
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                console.log(error)
            })
    }

    /*dialog item 点击*/
    itemClickListener(index, text) {


        switch (this.state.modalDataType) {
            case 'country':
                this.getProvinceInfo(1, countryData[index].name);
                this.setState({
                    selectCountry: text,
                    modalDialog: false,
                    postCode: countryData[index].postcode ? countryData[index].postcode : '',
                    countryId: countryData[index].id,
                    cityType: false,
                    districtType: false,
                    selectProvince: I18n.t('default.selectProvince'),
                    selectCity: I18n.t('default.selectCity'),
                    selectDistrictCity: I18n.t('default.selectDistrict'),
                });
                break;
            case 'region1':
                this.getProvinceInfo(2, provinceData[index].name);
                this.setState({
                    selectProvince: text,
                    modalDialog: false,
                    postCode: provinceData[index].postcode ? provinceData[index].postcode : '',
                    countryId: provinceData[index].id,
                    cityType: false,
                    districtType: false,
                    selectCity: I18n.t('default.selectCity'),
                    selectDistrictCity: I18n.t('default.selectDistrict'),

                });
                break;
            case 'region2':
                this.getProvinceInfo(3, cityData[index].name);
                this.setState({
                    selectCity: text,
                    modalDialog: false,
                    postCode: cityData[index].postcode ? cityData[index].postcode : '',
                    countryId: cityData[index].id,
                    districtType: false,
                    selectDistrictCity: I18n.t('default.selectDistrict'),
                });
                break;
            case 'region3':
                this.getProvinceInfo(4, districtData[index].name);
                this.setState({
                    selectDistrictCity: text,
                    modalDialog: false,
                    postCode: districtData[index].postcode ? districtData[index].postcode : '',
                    countryId: districtData[index].id,
                });
                break;


        }


    }

    /*showDialog*/
    showDialog(type) {
        switch (type) {
            case 0:
                this.setState({
                    modalDialog: true,
                    modalDataType: 'country'
                });
                break;
            case 1:
                if (provinceData.length > 0) {
                    this.setState({
                        modalDialog: true,
                        modalDataType: 'region1'
                    });
                }
                break;
            case 2:
                if (cityData.length > 0) {
                    this.setState({
                        modalDialog: true,
                        modalDataType: 'region2'
                    });
                }
                break;
            case 3:
                if (districtData.length > 0) {
                    this.setState({
                        modalDialog: true,
                        modalDataType: 'region3'
                    });
                }
                break;

        }

    }

    render() {
        let userData = this.props.editData;

        let _dataSource = this.state.countrySource;
        switch (this.state.modalDataType) {
            case 'region1':
                _dataSource = this.state.provinceSource;
                break;
            case 'region2':
                _dataSource = this.state.citySource;
                break;
            case 'region3':
                _dataSource = this.state.districtSource;
                break
        }


        return (
            <View style={[StyleUtils.flex, {backgroundColor: 'white'}]}>
                <Navigation
                    onClickLeftBtn={() => {
                        this.props.navigator.pop()
                    }}
                    leftButtonIcon={require('../../../res/images/ic_back.png')}
                    titleImage={require('../../../res/images/ic_ipar_logo.png')}
                />
                <ModalListUtils
                    close={() => {
                        this.setState({
                            modalDialog: false
                        })
                    }}
                    onPress={(index, text) => this.itemClickListener(index, text)}
                    visible={this.state.modalDialog}
                    dataSource={_dataSource}
                    dataParam={this.state.modalDataType}
                />

                <KeyboardAwareScrollView style={StyleUtils.flex}>
                    <View style={{padding: 16}}>
                        {ViewUtils.getTitleView(I18n.t('default.editAddressTitle'), I18n.t('default.editYourAccount'))}


                        {ViewUtils.getButtunMenu(this.state.selectCountry, () => this.showDialog(0))}
                        {ViewUtils.getButtunMenu(this.state.selectProvince, () => this.showDialog(1), {marginTop: 16})}
                        {this.state.cityType && ViewUtils.getButtunMenu(this.state.selectCity, () => this.showDialog(2), {marginTop: 16})}
                        {this.state.districtType && ViewUtils.getButtunMenu(this.state.selectDistrictCity, () => this.showDialog(3), {marginTop: 16})}

                        <Text style={[styles.defaultTv, StyleUtils.smallFont]}>{I18n.t('default.streetNumber')}</Text>
                        <IparInput
                            onChangeText={(value) => {
                                this.setState({streetNumber: value})
                            }}
                            placeholder={this.state.streetNumber ? this.state.streetNumber : userData && userData.street_name ? userData.street_name : I18n.t('default.streetNumber')}/>

                        <Text style={[styles.defaultTv, StyleUtils.smallFont]}>{I18n.t('default.buildingName')}</Text>

                        <IparInput
                            onChangeText={(value) => {
                                this.setState({buildingName: value})
                            }}
                            placeholder={this.state.buildingName ? this.state.buildingName : userData && userData.building ? userData.building : I18n.t('default.buildingName')}/>


                        <Text style={[styles.defaultTv, StyleUtils.smallFont]}>{I18n.t('default.postNumber')}</Text>
                        <IparInput
                            onChangeText={(value) => {
                                this.setState({postCode: value})
                            }}
                            placeholder={this.state.postCode ? this.state.postCode : userData && userData.postcode ? userData.postcode : I18n.t('default.postNumber')}/>


                        {ViewUtils.getButton(I18n.t('default.submit'), () => {
                            this.editAddress()
                        }, {marginTop: 50})}
                    </View>

                </KeyboardAwareScrollView>
            </View>
        )
            ;
    }


}

const styles = StyleSheet.create({
    defaultTv: {
        marginTop: 16,
        textAlign: 'left'

    },
    checkImage: {
        marginTop: 16,
        height: 20,
        width: 20
    }
});
